from flask import Flask, request, jsonify, Blueprint, Response

from langchain_3_ollama_history_chain import chain_ollama
# from langchain_5_ollama_rag import chain_milvus
from langchain_6_tool2 import agent as chain_weather2

app = Flask(__name__)


@app.route('/')
def index():
    return "Server is running"


@app.route("/chat1", methods=["GET"])
def chat1():
    # 普通问答
    question = request.args.get("question", "")

    if not question:
        return "Missing ?q=xxx", 400

    # post request.form.get('username')
    def generate():
        # 逐块 yield 给客户端
        for chunk in chain_ollama.stream({"question": question}):
            yield chunk.content

    # text/plain 方便 curl 调试；前端用 EventSource 可改成 text/event-stream
    return Response(generate(), mimetype='text/plain')


# @app.route("/chat2", methods=["GET"])
# def chat2():
#     # 从文档中回答
#     question = request.args.get("question", "")
#
#     if not question:
#         return "Missing ?q=xxx", 400
#
#     # post request.form.get('username')
#     def generate():
#         # 逐块 yield 给客户端
#         for chunk in chain_milvus.stream(question):
#             yield chunk.content
#
#     # text/plain 方便 curl 调试；前端用 EventSource 可改成 text/event-stream
#     return Response(generate(), mimetype='text/plain')

@app.route("/chat3", methods=["GET"])
def chat3():
    # 从文档中回答
    question = request.args.get("question", "")

    if not question:
        return "Missing ?q=xxx", 400

    # text/plain 方便 curl 调试；前端用 EventSource 可改成 text/event-stream
    return Response(chain_weather2.run({"input": question}), mimetype='text/plain')


# 可以把不同业务api放到不同类中管理
# api = Blueprint('api', __name__, url_prefix='/api')
#
# @api.route('/hello')
# def api_hello():
#     return jsonify({'msg': 'hello from blueprint'})
#
# app.register_blueprint(api)

# ------------ 6. 启动 ------------
if __name__ == '__main__':
    # debug=True 自动热重载，代码改完刷新即生效
    app.run(host='0.0.0.0', port=5000, debug=True)
